# import copy
from datetime import datetime
from PyQt5.QtCore import Qt, QAbstractTableModel, QModelIndex
from PyQt5.QtWidgets import QTableView
import traceback
import logging
from PyQt5 import QtCore,QtWidgets
from bpptablemodel import BTModel
import json
if __name__ == "__main__":
    import sys
    import logging
    from PyQt5.QtWidgets import QApplication
    from logging.handlers import RotatingFileHandler
    sys.stdout = open(sys.stdout.fileno(), mode='w', encoding='utf8', buffering=1)
    sys.stderr = open(sys.stderr.fileno(), mode='w', encoding='utf8', buffering=1)
    handlers=[RotatingFileHandler(filename="report.log", maxBytes=10*1024*1024, encoding='utf-8',backupCount=3),logging.StreamHandler(sys.stdout)]
    logging.basicConfig(level=logging.DEBUG,
                        format = '%(asctime)s - %(name)s - %(levelname)s -%(funcName)s - %(message)s',
                        handlers=handlers)
    logging.info('begin')
    # We'll create a table model/view for a list of these objects.

    # Create the QApplication.
    app = QApplication(sys.argv)

    # Create our object list.

    # Create the model/view.
    model = BTModel()
    w=QtWidgets.QWidget()

    view = QTableView(None)

    view.setModel(model)

    v=QtWidgets.QVBoxLayout(w)
    b0=QtWidgets.QPushButton("change object")
    def b0_click():
        objects[0].name="000000000"
        # model.getObjectRow(0).name="0000000"
        view.setFocus()
    b0.clicked.connect(b0_click)
    v.addWidget(b0)

    b=QtWidgets.QPushButton("add json")
    def b_click():
        model.beginReset(True);
        data=[[1,2,3],
        [2,4,5]]
        for one in data:
            j1=json.dumps(one)
            model.addRecord(j1)
        model.endReset();
        pass
    b.clicked.connect(b_click)
    v.addWidget(b)

    b2=QtWidgets.QPushButton("rm first")
    def b2_click():
        c = model.getObjectRow(0)
        model.rmObjects([c])
        pass
    b2.clicked.connect(b2_click)
    v.addWidget(b2)

    b3=QtWidgets.QPushButton("rm select")
    def b3_click():
        selections = view.selectionModel()
        list1 = selections.selectedIndexes()
        objs=[]
        for i in range(len(list1)):
            current = list1[i]
            obj =model.getObject(current)
            if obj in objs:
                pass
            else:
                objs.append(obj)
        model.rmObjects(objs)
    b3.clicked.connect(b3_click)
    v.addWidget(b3)

    v.addWidget(view)
    w.show()
    status = app.exec()

    sys.exit(status)
